package com.home.qh.webapp.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.home.qh.model.Country;
import com.home.qh.model.Region;
import com.home.qh.service.CountryManager;
import com.home.qh.service.RegionManager;

@Controller
public class CountryController {
	private transient final Log log = LogFactory.getLog(CountryController.class);
	private CountryManager countryManager;
	private RegionManager regionManager;
	
    @Autowired
    private ApplicationContext context;
    
    @Autowired
    public void setCountryManager(CountryManager countryManager) {
        this.countryManager = countryManager;
    }
    
    @Autowired
	public void setRegionManager(RegionManager regionManager){
		this.regionManager = regionManager;
	}
    
	
    @RequestMapping(value = "/admin/countryList.*", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView listCountries(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'handleRequest' method...");
        }
        
        Country countrySearch = new Country();
        String paramValue = request.getParameter("name");
        String paramRegionValue = request.getParameter("region");
        if (paramValue != null && !"".equalsIgnoreCase(paramValue.trim()) && !"null".equalsIgnoreCase(paramValue))
        {
        	countrySearch.setCode(paramValue);
        	countrySearch.setName(paramValue);
        }        
        
        if (paramRegionValue != null
				&& !"".equalsIgnoreCase(paramRegionValue.trim())
				&& !"null".equalsIgnoreCase(paramRegionValue)) {
			Long paramRegionId = null;
			try {
				paramRegionId = Long.parseLong(paramRegionValue);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (paramRegionId != null) {
				Region regionSearch = regionManager.get(paramRegionId);
				countrySearch.setRegion(regionSearch);
			}
        }
        ModelAndView view = new ModelAndView("admin/countryList");
        view.addObject("listRegions", regionManager.getAll());
        view.addObject("countrySearch", countrySearch);
        
        view.addObject("countryList", countryManager.getCountryByCountry(countrySearch, null, false, -1, -1));
        return view;

    }

}
